package com.yzt.sys.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yzt.base.dto.MenuDto;
import com.yzt.base.dto.ZTreeDTO;
import com.yzt.base.kit.Base;
import com.yzt.sys.entity.Menu;
import com.yzt.sys.kit.MenuKit;
import com.yzt.sys.service.IMenuService;

import io.swagger.annotations.Api;

/**
 * <p>
 * 系统菜单表 前端控制器
 * </p>
 *
 * @author Y
 * @since 2020-12-16
 */
@RestController
@RequestMapping("/sys/menu")
@Api(tags = "菜单")
public class MenuController {

	@Autowired
	private IMenuService menuService;

	@PostMapping("")
	public Base<Object> save(Menu menu) {
		boolean b = menuService.save(menu);
		if (b) {
			return Base.ok();
		}
		return Base.fail();
	}

	@GetMapping("/{id}")
	public Base<Menu> getById(@PathVariable("id") long id) {
		Menu menu = menuService.getById(id);
		if (menu != null) {
			Menu menu2 = menuService.getById(menu.getParentmenuId());
			if (menu2 != null) {
				menu.setParentmenuName(menu2.getMenuText());
			}
			return Base.okData(menu);
		}
		return Base.fail();
	}

	@PutMapping("")
	public Base<Object> update(Menu menu) {
		boolean b = menuService.updateById(menu);
		if (b) {
			return Base.ok();
		}
		return Base.fail();
	}

	@DeleteMapping("{id}")
	public Base<Object> delete(@PathVariable("id") long id) {
		List<Menu> menList = menuService.getMenuList(id);
		if (menList.size() > 0) {
			return Base.fail("请先删除子节点");
		}
		if (menuService.removeById(id)) {
			return Base.ok();
		}
		return Base.fail();
	}

	@GetMapping("list")
	public Base<PageInfo<Menu>> list(MenuKit kit) {
		PageInfo<Menu> pageInfo = PageHelper.startPage(kit.getPage(), kit.getLimit())
				.doSelectPageInfo(() -> menuService.list(Wrappers.<Menu>lambdaQuery()
						.like(StringUtils.isNotEmpty(kit.getMenuName()), Menu::getMenuText, kit.getMenuName())));
		return Base.okData(pageInfo);
	}

	@PostMapping("listDto")
	public Base<List<MenuDto>> listDto() {
		List<MenuDto> menuList = menuService.getMenuDtoList();
		return Base.okData(menuList);
	}

	@GetMapping("ztree")
	public Base<List<ZTreeDTO>> ztreeList() {
		return Base.okData(menuService.getMenuZTreeDto());
	}

}
